package com.ruoyi.pingan.fymodule.order.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.pingan.config.PayConfig;
import com.ruoyi.pingan.fymodule.account.entity.SxoSafetyUser;
import com.ruoyi.pingan.fymodule.account.enums.SourceEnum;
import com.ruoyi.pingan.fymodule.account.service.ISxoSafetyUserService;
import com.ruoyi.pingan.fymodule.order.entity.SxoSafetyOrder;
import com.ruoyi.pingan.fymodule.order.entity.SxoSafetySepAcc;
import com.ruoyi.pingan.fymodule.order.mapper.SxoSafetySepAccMapper;
import com.ruoyi.pingan.fymodule.order.service.ISxoSafetyOrderService;
import com.ruoyi.pingan.fymodule.order.service.ISxoSafetySepAccService;
import com.ruoyi.pingan.fymodule.thirdpa.model.dto.*;
import com.ruoyi.pingan.fymodule.thirdpa.model.vo.MemberTransactionVo;
import com.ruoyi.pingan.fymodule.thirdpa.model.vo.SubAccountQuestVo;
import com.ruoyi.pingan.fymodule.thirdpa.model.vo.TraFinalStatusQueryVo;
import com.ruoyi.pingan.fymodule.thirdpa.service.PaBondService;
import com.ruoyi.pingan.fymodule.thirdpa.service.PaOrderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

/**
 *
 * 平安分账订单分账 业务层实现
 *
 * @author wangy
 * @since 2025-06-19
 */
@Slf4j
@Service
public class SxoSafetySepAccServiceImpl extends ServiceImpl<SxoSafetySepAccMapper, SxoSafetySepAcc> implements ISxoSafetySepAccService {

    @Autowired
    private PaOrderService paOrderService;
    @Autowired
    private ISxoSafetyOrderService sxoSafetyOrderService;
    @Autowired
    private PaBondService paBondService;
    @Autowired
    private PayConfig payConfig;
    @Autowired
    private ISxoSafetyUserService sxoSafetyUserService;


    @Override
    public void execute6273_6271() {
        log.info("最终状态6271调平安接口开始：");
        log.info("分账状态查询；时间:{}", DateUtil.now());
        Date date = new Date();
        Date startTime = DateUtil.offsetDay(date, -1);
       // Date endTime = DateUtil.offsetMinute(date, -120);
        LambdaQueryWrapper<SxoSafetySepAcc> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SxoSafetySepAcc::getSepStatus, 3);
        queryWrapper.eq(SxoSafetySepAcc::getStatus, 0);
        queryWrapper.ge(SxoSafetySepAcc::getSepTime, DateUtil.format(startTime, "yyyy-MM-dd").concat(" 00:00:00"));
        queryWrapper.le(SxoSafetySepAcc::getSepTime,  DateUtil.now());
        queryWrapper.orderByAsc(SxoSafetySepAcc::getId);
        List<SxoSafetySepAcc> lists = this.list(queryWrapper);
        if (lists.isEmpty()) {
            log.info("分账状态查询；时间:{};数量：{}", DateUtil.now(), 0);
            return;
        }

        for (SxoSafetySepAcc sxoSafetySepAcc : lists) {
            try {
                //分账成功且返回见证受理流水号
                if (StrUtil.isEmpty(sxoSafetySepAcc.getJzbAcceptSeqNo())) {
                    continue;
                }
                TraFinalStatusQueryDto dto = new TraFinalStatusQueryDto();
                dto.setOldJzbAcceptSeqNo(sxoSafetySepAcc.getJzbAcceptSeqNo());
                TraFinalStatusQueryVo vo = paOrderService.traFinalStatusQuery(dto);
                if (!"6271".equals(vo.getTranType())) {
                    continue;
                }
                SxoSafetySepAcc acc = new SxoSafetySepAcc();
                SxoSafetyOrder order = new SxoSafetyOrder();
                order.setId(sxoSafetySepAcc.getSafetyOrderId());
                acc.setId(sxoSafetySepAcc.getId());

                //成功
                if ("0".equals(vo.getTranStatus())) {
                    String tranDateStr = vo.getTranDate().concat(vo.getTranTime());
                    Date tranDate = DateUtil.parse(tranDateStr);
                    //分账状态
                    acc.setSepStatus(1);
                    //分账时间
                    acc.setSepSuccTime(DateUtil.format(tranDate, "yyyy-MM-dd HH:mm:ss"));
                    acc.setSettleStatus(2);

                    order.setSepStatus(1);
                    order.setSepSuccTime(DateUtil.format(tranDate, "yyyy-MM-dd HH:mm:ss"));
                    this.updateById(acc);
                    sxoSafetyOrderService.updateById(order);
                }
                //失败
                if ("1".equals(vo.getTranStatus())) {
                    acc.setSepStatus(-1);
                    acc.setErrorMsg(vo.getTranDealStatusDesc());
                    order.setSepStatus(-1);
                    this.updateById(acc);
                    sxoSafetyOrderService.updateById(order);
                }

                if ("0".equals(vo.getTranStatus())) {
                    applySubsidy(sxoSafetySepAcc);

                    if (sxoSafetySepAcc.getNeedRevoke() != null && sxoSafetySepAcc.getNeedRevoke().equals(0)){
                        SubAccountQuestDto subAccountQuestDto = new SubAccountQuestDto();
                        subAccountQuestDto.setSepAccId(sxoSafetySepAcc.getId());
                        SubAccountQuestVo voR= paOrderService.subAccountCancel(subAccountQuestDto);
                        log.info("execute6273_6271时间:{};撤退分账结果：{}", DateUtil.now(), JSON.toJSONString(voR));
                    }
                }

            } catch (Exception e) {
                log.error("execute6273_6271时间:{};异常：{}", DateUtil.now(), e.getMessage());
            }
        }
        log.info("分账状态查询；时间:{}；数量：{}", DateUtil.now(), lists.size());
    }

    @Override
    public void executeSettlement(SettlementDto dto) {
        log.info("分账提现结算查询；时间:{}", DateUtil.now());
        Date date = new Date();
        Date startTime = DateUtil.offsetMonth(date, -1);
        LambdaQueryWrapper<SxoSafetySepAcc> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SxoSafetySepAcc::getSepStatus, 1);
        queryWrapper.eq(SxoSafetySepAcc::getSettleStatus, 2);
        queryWrapper.eq(SxoSafetySepAcc::getStatus, 0);
        queryWrapper.eq(SxoSafetySepAcc::getShopId, dto.getShopId());
        queryWrapper.eq(SxoSafetySepAcc::getOrderMonth,  DateUtil.format(startTime, "yyyyMMdd"));
        queryWrapper.orderByAsc(SxoSafetySepAcc::getId);
        List<SxoSafetySepAcc> lists = this.list(queryWrapper);
        if (lists.isEmpty()) {
            log.info("分账提现结算查询；时间:{};数量：{}", DateUtil.now(), 0);
            return;
        }

        //log.info("分账提现结算查询；时间:{}；数量：{}", DateUtil.now(), lists.size());
    }

    private void applySubsidy(SxoSafetySepAcc sxoSafetySepAcc) {
        SxoSafetyOrder sxoSafetyOrder = sxoSafetyOrderService.getById(sxoSafetySepAcc.getSafetyOrderId());
        if (sxoSafetyOrder == null) {
            log.info("订单{}错误", sxoSafetySepAcc.getSafetyOrderId());
            return;
        }
        if (sxoSafetyOrder.getPlatTotalAmt() == null){
            log.info("订单{}无需分账补贴金额", sxoSafetySepAcc.getSafetyOrderId());
            return;
        }
        BigDecimal platTotalAmt = new BigDecimal(sxoSafetyOrder.getPlatTotalAmt());
        if (platTotalAmt.compareTo(new BigDecimal("0")) <= 0) {
            log.info("订单{}补贴金额:{}", sxoSafetyOrder.getId(), sxoSafetyOrder.getPlatTotalAmt());
            return;
        }

        SxoSafetyUser safetyUser = sxoSafetyUserService.findUser(sxoSafetyOrder.getShopId(), SourceEnum.SHOP.getCode());
        if (safetyUser == null) {
            log.info("商家未认证:{}", sxoSafetyOrder.getShopId());
            return;
        }

        MemberTransactionDto dto = new MemberTransactionDto();
        dto.setSafetyOrderId(sxoSafetyOrder.getId());
        dto.setFunctionType("0");
        dto.setFunctionFlag(6);
        dto.setOutSubAcctNo(payConfig.getSubAcctNo13());
        dto.setOutMemberCode(payConfig.getSubAcctNo13());
        dto.setOutSubAcctName("营销子台账");

        dto.setInSubAcctNo(safetyUser.getSubAcctNo());
        dto.setInMemberCode(safetyUser.getTranNetMemberCode());
        dto.setInSubAcctName(StrUtil.isEmpty(safetyUser.getSubAcctName()) ? safetyUser.getMemberName() : safetyUser.getSubAcctName());

        dto.setTranAmt(sxoSafetyOrder.getPlatTotalAmt());
        dto.setTranFee("0.00");

        dto.setSafetyAccId(sxoSafetySepAcc.getId());
        dto.setRemark("商家补贴金额");
        MemberTransactionVo vo = paBondService.memberTransaction(dto);
        log.info("订单{}商家补贴:{}", sxoSafetyOrder.getId(), JSON.toJSONString(vo));
    }
}